package com.example.park.park

import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.example.lib_base.entity.ParkBean
import com.example.lib_base.entity.ParkBeanItem
import com.example.lib_base.mvvm.BaseViewModel
import com.example.lib_base.net.ApiService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import okhttp3.RequestBody
import javax.inject.Inject

@HiltViewModel
class ParkViewModel @Inject constructor(val apiService: ApiService):BaseViewModel(){
    val addCarSuccess=MediatorLiveData<ParkBeanItem>()
    val getParkByIdData=MediatorLiveData<ParkBeanItem>()
    val updateSuccess=MediatorLiveData<ParkBeanItem>()
    val deleteSuccess=MediatorLiveData<Boolean>()
    fun getParkByType(para:String,type:String):Flow<PagingData<ParkBeanItem>>{
        return Pager(config = PagingConfig(pageSize = 10), pagingSourceFactory = {
            ParkDataSource(apiService,para, type)
        }).flow.cachedIn(viewModelScope)
    }

    fun addSuccess(item: ParkBeanItem){
        httpRequest({apiService.getAddPark(toBody(item))},addCarSuccess::postValue)
    }
    fun getParkById(id:Int){
        httpRequest({apiService.getParkById(id)},getParkByIdData::postValue)
    }
    fun update(id:Int,item: ParkBeanItem){
        httpRequest({apiService.upDate(id,toBody(item))},updateSuccess::postValue)
    }
    fun delete(id:Int){
        httpRequest({apiService.deletePark(id)},deleteSuccess::postValue)
    }
}